package corej.course.thread;

import java.util.*;

public class TestObserver {
    public static void main(String[] args) {
        Stock s = new Stock();
        StockListener s1 = new StockListener1();
        StockListener s2 = new StockListener2();

        s.addStockListener(s1);
        s.addStockListener(s2);

        s.fire();

        s.removeStockListener(s2);

        s.fire();
    }
}

// �¼�����

class StockEvent extends EventObject {
    public StockEvent(Object source) {
        super(source);
    }
}

// ����ӿ�
interface StockListener extends EventListener {
    void increase(StockEvent se);

    void decrease(StockEvent se);
}

// �¼�Դ
class Stock {
    // element: StockListener Object
    private List listeners = new ArrayList();

    public void addStockListener(StockListener listener) {
        this.listeners.add(listener);
    }

    public void removeStockListener(StockListener listener) {
        this.listeners.remove(listener);
    }

    public void fire() {
        StockEvent e = new StockEvent(this);
        for (int day = 1; day <= 5; day++) {
            int i = (int) (Math.random() * 10000) % 2;
            System.out.print("Day " + day + ":");
            if (i == 0)
                System.out.println("��������");
            else
                System.out.println("���е���");

            Iterator it = listeners.iterator();
            while (it.hasNext()) {
                StockListener sl = (StockListener) it.next();
                if (i == 0) {
                    sl.increase(e);
                } else {
                    sl.decrease(e);
                }
            }

        }
    }
}

class StockListener1 implements StockListener {
    public void increase(StockEvent e) {
        System.out.println("Ͷ����1 ���");
    }

    public void decrease(StockEvent e) {
        System.out.println("Ͷ����1 ���");
    }
}

class StockListener2 implements StockListener {
    public void increase(StockEvent e) {
        System.out.println("Ͷ����2 ���");
    }

    public void decrease(StockEvent e) {
        System.out.println("Ͷ����2 ���");
    }
}
